package com.walala.dispatcher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.walala.dispatcher.global.Global;
import com.walala.dispatcher.server.UdpServer;
import com.walala.dispatcher.service.DispatcherService;
import com.walala.dispatcher.utils.IPUtils;
import com.walala.dispatcher.utils.Utils;
import com.walala.dispatcher.zk.ZkClient;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

public class Main {

	private static Logger logger = LoggerFactory.getLogger(Main.class);
	
	static {
		logger.info("[static] config file base path {}", Utils.getRealPath());
		LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
		JoranConfigurator configurator = new JoranConfigurator();
		configurator.setContext(lc);
		lc.reset();
		try {
			configurator.doConfigure(Utils.getRealPath() + "/config/logback.xml");
		} catch (JoranException e) {
			logger.error("[static] error is: ", e);
		}
		StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
	}

	public static void main(String[] args) {
		
		//启动u服务
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				UdpServer.init(Global.server_ip,Global.server_port);
			}
		}).start();
		
		//启动zk并上报
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					ZkClient instance = ZkClient.getInstance();
					instance.initZkClient(Global.zk_addr);
				
					String address = Global.server_ip + ":" + Global.server_port;
					ZkClient.getInstance().createNode(Global.dispatcher_server_path + address, null,false);
					
					logger.info("调度服务已注册");
					
				} catch (Exception e) {
					logger.error("server start occoured a error when regist server to zk",e);
				}
			}
		}).start();
		
		//启动定时服务检查
		DispatcherService.init();
		
	}
	
}
